package demo.example.service.impl;

import demo.example.exception.TTException;
import demo.example.exception.TTExceptionEnum;
import demo.example.model.dao.UserMapper;
import demo.example.model.pojo.User;
import demo.example.service.UserService;
import demo.example.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

/**
 * @Date 2022/7/13 19:29
 * @Created by wangle
 * @Description
 */
@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    UserMapper userMapper;


    /**
     * 测试数据库查询功能
     * @return
     */
    @Override
    public User getUser() {
      User user = userMapper.selectByPrimaryKey(1);
        return user;
    }

    @Override
    public User login(String userName, String password) {

        String md5Password = null;
        try {
            md5Password = MD5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userMapper.selectLogin(userName, md5Password);
        if (user == null) {
            throw new TTException(TTExceptionEnum.WRONG_PASSWORD);
        }
        return user;
    }

    @Override
    public void register(String userName, String password) throws TTException {
        //查询用户名是否存在，是否重名
        User result = userMapper.selectByName(userName);
        if(result != null) {
            throw new TTException(TTExceptionEnum.NAME_EXISTED);

        }
        // 写到数据库
        User user = new User();
        user.setUsername(userName);
//        //常规密码
//        user.setPassword(password);
        //MD5工具处理密码
        try {
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        int count = userMapper.insertSelective(user);
        if(count == 0) {
            throw new TTException(TTExceptionEnum.INSERT_FAILED);
        }

    }

    @Override
    public User selectByName(String userName) {
        User user = userMapper.selectByName(userName);
        return user;
    }




}
